// src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

// 定义状态
const state = {
    firstLoadFinished: false, // 首次加载是否完成
    user: {
        avatar: '',
        createTime: '',
        nickName: '',
        openId: "",
        phone: '',
        userId: '',
        userName: '',
        expireDate: '', // 会员过期时间
    },
    children: [], // 子女信息
    defaultChild: {},
    scaleList: [], // 试题列表
    menuNav: 'home', // 底部导航选中
    msgNum: 0, // 消息数量
    token: '', // 登录auth
    systemInfo: {}, // 设备信息
    loadCount: 0, // 加载次数
    expireDays: 0, // 过期天数
};

// 定义改变状态的方法
const mutations = {
    set_user(state, user) {
        state.user = {
            ...state.user,
            ...user
        };
        if (user.expireDate && user.expireDate != '无支付记录') {
            const date1 = new Date();
            const date2 = new Date(user.expireDate);

            // 计算时间差（以毫秒为单位）  
            const timeDifference = date2 - date1;

            // 将时间差转换为天数（1天 = 24小时 * 60分钟 * 60秒 * 1000毫秒）  
            const dayDifference = timeDifference / (1000 * 60 * 60 * 24),
                expireDays = parseInt(dayDifference) + (dayDifference % 1 > 0 ? 1 : 0);
            state.expireDays = expireDays < 0 ? 0 : expireDays;
        } else {
            state.expireDays = 0;
        }
    },
    set_children(state, children) {
        state.children = children;
        let count = 0;
        for (let i = 0, len = children.length; i < len; i++) {
            if (children[i].isDefault == '1') {
                state.defaultChild = children[i];
                count++;
                break;
            }
        }
        if (count == 0) {
            state.defaultChild = {};
        }
    },
    set_defaultChild(state, child) {
        state.defaultChild = child;
    },
    set_scaleList(state, scaleList) {
        state.scaleList = scaleList;
    },
    changeMenuNav(state, nav) {
        state.menuNav = nav;
    },
    set_token(state, token) {
        state.token = token;
    },
    set_systemInfo(state, systemInfo) {
        state.systemInfo = systemInfo;
    },
    set_loadCount(state) {
        state.loadCount++;
    },
    set_VIPTime(state) {
        // 获取会员到期时间
        // 假设从后台获取
        state.user.expireDate = '2024-12-31';
    },
    set_firstLoadFinished(state) {
        state.firstLoadFinished = true;
    }
};

// 创建store
export default new Vuex.Store({
    state,
    mutations,
});